/*
** remote_write.c for pud in mrcellophane/libpud
** 
** Made by solomon hykes
** Login   <torgau@gmail.com>
** 
** Started on  Mon May 16 23:49:58 2005 solomon hykes
** Last update Thu Jul 14 04:33:27 2005 solomon hykes
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "pud.h"

int	main(int argc, char **argv)
{
  int	pid;
  u_long	addr;
  long	len;

  if (argc < 4)
    {
      fprintf(stderr, "Usage: %s pid addr length\n\nRead <length> bytes from process <pid> at address <addr>\n", argv[0]);
      exit(1);
    }
  pid = atoi(argv[1]);
  addr = (u_long)strtoul(argv[2], (char **)NULL, 16);
  len = atoi(argv[3]);
  fprintf(stderr, "pid=%d, addr=%p, len=%d\n", pid, addr, len);
  pscat(pid, addr, len);
}

int	pscat(int pid, u_long addr, int len)
{
  pud_process	*proc;
  pud_event	*event;
  char		*buf = malloc(len + 1);
  int		ret;

  proc = pud_attach(pid);
  if (proc == NULL)
    {
      perror("pud_attach");
      exit(1);
    }
  event = pud_next_event(proc);
  if (event == NULL)
    {
      perror("pud_next_event");
      pud_detach(proc);
      exit(1);
    }
  ret = pud_mem_read(proc, addr, buf, len);
  if (ret == -1)
    {
      perror("pud_mem_read()");
      pud_detach(proc);
      exit(1);
    }
  buf[ret] = 0;
  write(1, buf, ret);
  pud_detach(proc);
  return (ret);
}
